//package com.ytjj.qmyx.mall.config;
//
//import com.ytjj.qmyx.mall.enums.MQFailLogStatusEnums;
//import com.ytjj.qmyx.mall.enums.MQFailLogTypeEnums;
//import com.ytjj.qmyx.mall.model.MqFailLog;
//import com.ytjj.qmyx.mall.service.MqFailLogService;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.amqp.core.Message;
//import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
//import org.springframework.amqp.rabbit.connection.ConnectionFactory;
//import org.springframework.amqp.rabbit.connection.CorrelationData;
//import org.springframework.amqp.rabbit.core.RabbitTemplate;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.cloud.context.config.annotation.RefreshScope;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//
//import java.net.URI;
//import java.util.Date;
//
///**
// * 消息发送失败回调函数
// */
//@Slf4j
//@Configuration
//@RefreshScope
//public class RabbitConfig {
//    private MqFailLogService mqFailLogService;
//    @Value("${spring.rabbitmq.host:}")
//    private String host;
//    @Value("${spring.rabbitmq.username}")
//    private String username;
//    @Value("${spring.rabbitmq.password}")
//    private String password;
//    @Value("${spring.rabbitmq.virtualHost:}")
//    private String virtualHost;
//    @Value("${spring.profiles.active}")
//    private String profiles;
//
//    public RabbitConfig(MqFailLogService mqFailLogService) {
//        this.mqFailLogService = mqFailLogService;
//    }
//
//    @Bean
//    public ConnectionFactory connectionFactory() {
//        CachingConnectionFactory cachingConnectionFactory = null;
//        if ("pd".equals(profiles)) {
////            URI uri = URI.create(host);
//            cachingConnectionFactory = new CachingConnectionFactory(host);
//            cachingConnectionFactory.setVirtualHost(virtualHost);
//        }else {
//            cachingConnectionFactory = new CachingConnectionFactory(host, 5672);
//        }
//        cachingConnectionFactory.setUsername(username);
//        cachingConnectionFactory.setPassword(password);
//        cachingConnectionFactory.setCacheMode(CachingConnectionFactory.CacheMode.CHANNEL);
////        cachingConnectionFactory.setConnectionCacheSize(10);
//        cachingConnectionFactory.setConnectionLimit(500);
//        cachingConnectionFactory.setChannelCacheSize(80);
//        cachingConnectionFactory.setChannelCheckoutTimeout(3000);
//        cachingConnectionFactory.setPublisherConfirms(true);//发送到交换机确认
//        cachingConnectionFactory.setPublisherReturns(true);//发送到队列确认
//        return cachingConnectionFactory;
//    }
//
//    @Bean
//    public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory){
//        RabbitTemplate rabbitTemplate = new RabbitTemplate();
//        rabbitTemplate.setConnectionFactory(connectionFactory);
//        //设置开启Mandatory,才能触发回调函数,无论消息推送结果怎么样都强制调用回调函数
//        rabbitTemplate.setMandatory(true);
//        rabbitTemplate.setUsePublisherConnection(true);
//
//        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
//            @Override
//            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
//                log.info("ConfirmCallback:     " + "确认情况：" + ack);
//                if (!ack) {
//                    MqFailLog mqFailLog = generateObj(null == correlationData ? "" : correlationData.getReturnedMessage().toString(), cause, null);
//                    int count = mqFailLogService.insert(mqFailLog);
//                    if (count <= 0) {
//                        log.error("ConfirmCallback记录数据库失败:" + correlationData + ", 原因：" + cause);
//                    }
//                }
//            }
//        });
//
//        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
//            /**
//             * @param message 消息
//             * @param replyCode 回应码
//             * @param replyText 回应信息
//             * @param exchange 交换机
//             * @param routingKey 路由键
//             */
//            @Override
//            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
//                MqFailLog mqFailLog = generateObj(message.toString(), replyText, routingKey);
//                int count = mqFailLogService.insert(mqFailLog);
//                if (count <= 0) {
//                    log.error("ReturnCallback记录数据库失败:" + message + ", 原因：" + replyText);
//                }
//            }
//        });
//
//        return rabbitTemplate;
//    }
//
//    private MqFailLog generateObj(String message, String reason, String queue) {
//        MqFailLog mqFailLog = MqFailLog.builder()
//                .type(MQFailLogTypeEnums.PRODUCER.getValue())
//                .message(message.toString())
//                .createTime(new Date())
//                .reason(reason)
//                .queue(queue)
//                .status(MQFailLogStatusEnums.WAIT.getValue())
//                .build();
//        return mqFailLog;
//    }
//}
